<template>
  <el-card class="creation">
    <el-alert
      title="'新增标签'为可选项，你可以新增想写的标签，新增完标签后可以从'标签'里选择你新增的新增标签，你可以在标签选择中为帖子选择多个标签"
      type="warning"
      show-icon
      :closable="false"
    ></el-alert>
    <el-form
      :model="creationForm"
      :rules="creationFormRules"
      ref="creationFormRef"
      label-width="65px"
    >
      <el-form-item label="标题：" prop="title">
        <el-input
          type="textarea"
          placeholder="请输入标题"
          v-model="creationForm.title"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="标签：" prop="tag">
            <el-cascader
              v-model="creationForm.tag"
              :options="tagOptions"
              @change="getChangeTag"
              style="width: 100%"
              :props="{ multiple: true }"
              :clearable="true"
            ></el-cascader></el-form-item
        ></el-col>
        <el-col class="addTag" :span="12">
          <el-form-item label="新增标签：">
            <el-select
              v-model="tagModule"
              placeholder="请选择"
              @change="getChangeTagModule"
              style="width: 30%"
            >
              <el-option
                v-for="item in tagModuleOptions"
                :key="item.tagModuleId"
                :label="item.tagModuleName"
                :value="item.tagModuleId"
              >
              </el-option>
            </el-select>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput"
              >+ New Tag</el-button
            >
            <el-button
              v-show="inputValue"
              type="primary"
              @click="addTag"
              @keyup.enter.native="addTag"
              class="button-new-tag"
              size="small"
              >新增</el-button
            >
          </el-form-item></el-col
        >
      </el-row>
    </el-form>
    <Editor ref="getEditor" />
    <div class="creation-button">
      <el-button @click="clear(creationFormRef)">清空</el-button>
      <el-button type="primary" @click="submit(creationFormRef)"
        >提交</el-button
      >
    </div>
  </el-card>
</template>

<script setup lang="ts">
import Editor from '@/components/WangEditor.vue';
import { ref, reactive, onMounted,nextTick, getCurrentInstance, ComponentInternalInstance } from 'vue'
import { FormRules, ElMessage, ElMessageBox } from 'element-plus'
import { FormInstance } from 'ant-design-vue';

const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const proxy = appContext.config.globalProperties;

// 创作表单信息
interface CreateForm {
  title: String
  tag: []
  tagId: []
}
const creationForm = reactive<CreateForm>({
  // 标题
  title: '',
  // 选中的标签
  tag: [],
  // 选中的标签id
  tagId: [],
}) as any;
// 创作表单验证
const creationFormRules = reactive<FormRules<CreateForm>>({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  tag: [{ required: true, message: '请选择标签', trigger: 'blur' }],
})
const creationFormRef = ref<FormInstance>();
// 标签信息
interface TagOptions {
  value: String
  label: String
  children: [{
    value: String
    label: String
  }]
}
const tagOptions = ref<TagOptions[]>([]) as any;
// 标签模块信息
const tagModuleOptions = ref([]) as any;
// 获取标签模块和模块id
const tagModule = ref('');
const tagModuleId = ref(0);
// 新增标签
const dynamicTags = ref([]) as any;
// 新增标签输入框是否可见
const inputVisible = ref(false);
// 新增标签名
const inputValue = ref('');
// Editor的ref
const getEditor = ref();
const saveTagInput = ref();

onMounted(() => {
  getAllTag();
  getAllTagModule();
});

// 获取所有标签信息
function getAllTag() {
  proxy.$request.tag.getAllTag().then((res: any) => {
    console.log('res===>',res);

    tagOptions.value = [];
    res.data.forEach((item: any, index: any) => {
      tagOptions.value.push({
        value: item.tagModuleName,
        label: item.tagModuleName,
        children: []
      });
      item.tagList.forEach((item: any) => {
        tagOptions.value[index].children.push({
          value: item.tagId,
          label: item.tagContent,
        });
      });
    });
  });
};
// 获取所有标签模块
function getAllTagModule() {
  proxy.$request.tag.getAllTagModule().then((res: any) => {
    console.log('res===>', res);

    tagModuleOptions.value = res.data;
  });
};
// 当级联选择器选中节点变化时触发
function getChangeTag(value: any) {
  creationForm.tagId = [];
  if (value.length === 0) {
    return (creationForm.tag = []);
  }
  value.forEach((item: any, index: any) => {
    creationForm.tagId[index] = item[1];
  });
};
// 当选择器选中节点变化时触发
function getChangeTagModule(value: any) {
  tagModuleId.value = value;
};
// 删除新增标签
// function handleClose(tag: any) {
//   dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
// };
// 清空文本框的数据
function clear(formEl: FormInstance | undefined) {
  getEditor.value.clear();
  if (!formEl) return;
  formEl.resetFields();
};
// 显示新增标签输入框
function showInput() {
  if (!tagModule.value) {
    return ElMessage({
      message: '请输入选择标签模块',
      type: 'error',
      duration: 1000,
    });
  }
  inputVisible.value = true;
  nextTick(() => {
    saveTagInput.value.focus();
  });
};
// 点击或者按下enter键后新增标签
function addTag() {
  if (!inputValue.value) {
    return ElMessage({
      message: '请输入新增标签内容',
      type: 'error',
      duration: 1000,
    });
  }
  proxy.$request.tag.getAllTag().then((res: any) => {
    dynamicTags.value = [];
    res.data.forEach((item: any) => {
      item.tagList.forEach((item: any) => {
        dynamicTags.value.push(item.tagContent);
      });
    });
    // 新增标签
    let InputValue = inputValue.value;
    if (dynamicTags.value.indexOf(inputValue) !== -1) {
      inputVisible.value = false;
      inputValue.value = '';
      return ElMessage({
        message: '新增标签内容与原有标签重复',
        type: 'error',
        duration: 1000,
      });
    }
    proxy.$request.tag
      .addTag({
        tagContent: InputValue,
        tagModuleId: tagModuleId.value,
      })
      .then((res: any) => {
        ElMessage({
          message: res.msg,
          type: 'success',
          duration: 1000,
        });
        getAllTag();
      });
    inputVisible.value = false;
    inputValue.value = '';
  });
};
// 提交数据
function submit(formEl: FormInstance | undefined) {
  let value = getEditor.value.getValue();
  if (value == '<p><br></p>') {
    return ElMessage({
      message: '请先输入创作内容',
      type: 'error',
      duration: 1000,
    });
  }
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (!valid) return;
    ElMessageBox.confirm('此操作将发布帖子, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        proxy.$request.discussPost
          .newPost({
            content: value,
            status: 0,
            tags: creationForm.tagId,
            title: creationForm.title,
            type: 0,
            userId: proxy.$storage.getItem('userInfo').userId,
          })
          .then((res: any) => {
            ElMessage({
              message: res.msg,
              type: 'success',
              duration: 1000,
            });
            proxy.$router.push('/community');
          });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消操作',
          duration: 1000,
        });
      });
  });
};
</script>

<style lang="less" scoped>
.creation {
  .el-alert {
    margin-bottom: 20px;
  }

  .addTag {
    /deep/ .el-form-item__label {
      width: 100px !important;
    }

    .button-new-tag {
      margin-left: 10px;
      height: 32px;
      line-height: 30px;
      padding-top: 0;
      padding-bottom: 0;
    }

    .input-new-tag {
      width: 120px;
      margin-left: 10px;
      vertical-align: bottom;
    }
  }

  .creation-button {
    float: right;
    width: 180px;

    .el-button {
      margin: 20px 0 20px 20px;
    }
  }
}
</style>
